<template>
  <div class="container fade-in">
    <div class="header">
      <h2 class="section-title">订单详情</h2>
      <div class="actions">
        <router-link to="/orders" class="btn secondary">返回列表</router-link>
        <button class="btn secondary" @click="loadDetail">刷新</button>
      </div>
    </div>

    <div class="card slide-up" style="animation-delay: 0.2s">
      <div v-if="loading" class="loading-state">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      <div v-else-if="!detail" class="empty-state">
        <div class="icon">❓</div>
        <h3>未找到该订单</h3>
        <p>请返回列表重新选择</p>
      </div>
      <div v-else class="detail-grid">
        <div class="row"><div class="label">订单编号</div><div class="value">{{ detail.orderCode || '-' }}</div></div>
        <div class="row"><div class="label">支付方式</div><div class="value">{{ payMethodText(detail.payMethod) }}</div></div>
        <div class="row"><div class="label">支付状态</div><div class="value">{{ paymentStatusText(detail.paymentStatus) }}</div></div>
        <div class="row"><div class="label">订单金额</div><div class="value">{{ formatAmount(detail.orderAmount) }}</div></div>
        <div class="row"><div class="label">支付金额</div><div class="value">{{ formatAmount(detail.payAmount) }}</div></div>
        <div class="row"><div class="label">优惠金额</div><div class="value">{{ formatAmount(detail.discountAmount) }}</div></div>
        <div class="row"><div class="label">结算金额</div><div class="value">{{ formatAmount(detail.settlementAmount) }}</div></div>
        <div class="row"><div class="label">手续费</div><div class="value">{{ formatAmount(detail.commission) }}</div></div>
        <div class="row"><div class="label">平台服务费</div><div class="value">{{ formatAmount(detail.platformServiceFee) }}</div></div>
        <div class="row"><div class="label">所属商户</div><div class="value">{{ detail.merchantName || detail.merchantId || '-' }}</div></div>
        <div class="row"><div class="label">所属门店</div><div class="value">{{ detail.storeName || detail.storeId || '-' }}</div></div>
        <div class="row"><div class="label">收款码</div><div class="value">{{ detail.codeName || detail.codeId || '-' }}</div></div>
        <div class="row"><div class="label">创建时间</div><div class="value">{{ formatDate(detail.creationTime) }}</div></div>
        <div class="row"><div class="label">支付时间</div><div class="value">{{ formatDate(detail.paymentTime) }}</div></div>
        <div class="row"><div class="label">退款状态</div><div class="value">{{ refundStatusText(detail.refundStatus) }}</div></div>
        <div class="row"><div class="label">累计退款金额</div><div class="value">{{ formatAmount(detail.totalRefundAmount) }}</div></div>
        <div class="row"><div class="label">退款次数</div><div class="value">{{ detail.refundCount ?? 0 }}</div></div>
        <div class="row"><div class="label">结算日期</div><div class="value">{{ formatDate(detail.settlementDate) }}</div></div>
        <div class="row"><div class="label">分账日期</div><div class="value">{{ formatDate(detail.dividedDate) }}</div></div>
      </div>
    </div>

    <div class="card slide-up" style="animation-delay: 0.3s">
      <div class="table-header">
        <h3>退款记录</h3>
        <div class="table-actions">
          <button class="btn secondary" @click="loadRefunds">
            <span class="icon">🔄</span>
            刷新
          </button>
        </div>
      </div>
      <table class="table">
        <thead>
          <tr>
            <th>退款编号</th>
            <th>退款金额</th>
            <th>原订单金额</th>
            <th>手续费</th>
            <th>退款时间</th>
            <th>状态</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="refundLoading" class="loading-row">
            <td colspan="6" class="loading"><div class="spinner"></div>加载中...</td>
          </tr>
          <tr v-else-if="refunds.length === 0" class="empty-row">
            <td colspan="6" class="empty">暂无退款记录</td>
          </tr>
          <template v-else>
            <tr v-for="r in refunds" :key="r.id" class="data-row">
              <td>{{ r.outRefundNo || '-' }}</td>
              <td>{{ formatAmount(r.refundAmount) }}</td>
              <td>{{ formatAmount(r.originalAmount) }}</td>
              <td>{{ formatAmount(r.procedureFee) }}</td>
              <td>{{ formatDate(r.refundTime) }}</td>
              <td>{{ refundRecordStatusText(r.status) }}</td>
            </tr>
          </template>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import { OrderService, type OrderDetail, type OrderRefundRecordItem, paymentStatusText, payMethodText } from '../services/order'
import { isSuccess } from '../services/types'

const route = useRoute()
const id = String(route.params.id || '')
const loading = ref(false)
const detail = ref<OrderDetail | null>(null)

const refundLoading = ref(false)
const refunds = ref<OrderRefundRecordItem[]>([])

function formatDate(v?: string) {
  if (!v) return '-'
  try { return new Date(v).toLocaleString('zh-CN') } catch { return v }
}
function formatAmount(v?: number) {
  if (v == null) return '-'
  return (v / 100).toFixed(2)
}

function refundStatusText(s?: number): string {
  switch (s) {
    case 0: return '未退款'
    case 1: return '部分退款'
    case 2: return '全额退款'
    default: return '未知'
  }
}
function refundRecordStatusText(s?: number): string {
  switch (s) {
    case 1: return '退款成功'
    case 0: return '退款失败'
    default: return '未知'
  }
}

async function loadDetail() {
  loading.value = true
  try {
    const res = await OrderService.getOrderDetail(id)
    if (isSuccess(res)) {
      detail.value = res.data || null
    } else {
      detail.value = null
      console.warn('获取订单详情失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    loading.value = false
  }
}

async function loadRefunds() {
  if (!id) return
  refundLoading.value = true
  try {
    const res = await OrderService.getOrderRefundRecordList(id)
    if (isSuccess(res)) {
      refunds.value = res.data || []
    } else {
      refunds.value = []
      console.warn('获取退款记录失败:', res?.message)
    }
  } catch (e) {
    console.error('接口异常:', e)
  } finally {
    refundLoading.value = false
  }
}

onMounted(async () => {
  await loadDetail()
  await loadRefunds()
})
</script>

<style scoped>
.detail-grid { display: grid; grid-template-columns: 200px 1fr; gap: 12px; }
.row { display: contents; }
.label { color: var(--text-secondary); }
.value { color: var(--text); font-weight: 500; }
.text-secondary { color: var(--text-secondary); }
.loading-state, .empty-state { text-align: center; padding: var(--space-6); color: var(--text-secondary); }
.loading-spinner { width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--primary-600); border-radius: 50%; display:inline-block; animation: spin 0.8s linear infinite; margin-right: 8px; }
.table { width: 100%; border-collapse: collapse; }
.table th, .table td { padding: 12px; border-bottom: 1px solid var(--border); }
.table-header { display:flex; align-items:center; justify-content:space-between; padding: var(--space-4); }
.table-actions { display:flex; gap: var(--space-3); }
.spinner { width: 16px; height: 16px; border: 2px solid var(--border); border-top-color: var(--primary-600); border-radius: 50%; display:inline-block; animation: spin 0.8s linear infinite; margin-right: 8px; }
@keyframes spin { to { transform: rotate(360deg); } }
</style>

